package com.cin.cma.common.model;

import com.alibaba.fastjson2.JSON;
import lombok.Data;

import java.io.Serializable;


@Data
public class ApiResponse<T> implements Serializable {

    /**
     * 业务处理成功/失败
     */
    private Boolean success;
    /**
     * 业务处理失败内容
     */
    private ApiErrorInfo error;
    /**
     * 业务处理成功结果
     */
    private T data;

    public ApiResponse() {
        this.success = true;
    }

    public static ApiResponse<?> success() {
        return new ApiResponse<>();
    }

    public static <T> ApiResponse<T> success(T data) {
        ApiResponse<T> apiResponse = new ApiResponse<>();
        apiResponse.setSuccess(true);
        apiResponse.setData(data);
        return apiResponse;
    }

    public static <T> ApiResponse<T> fail(ApiErrorInfo error) {
        ApiResponse<T> apiResponse = new ApiResponse<>();
        apiResponse.setSuccess(false);
        apiResponse.setError(error);
        return apiResponse;
    }

    public static <T> ApiResponse<T> fail(String code, String message) {
        ApiResponse<T> apiResponse = new ApiResponse<>();
        apiResponse.setSuccess(false);
        ApiErrorInfo errorInfo = new ApiErrorInfo("");
        errorInfo.setCode(code);
        errorInfo.setMessage(message);
        apiResponse.setError(errorInfo);
        return apiResponse;
    }

    /**
     * 构建统一返回
     *
     * @param model
     * @param <T>
     * @return
     */
    public static <T> ApiResponse<T> buildApiResponse(ApiResponse<?> model) {
        ApiResponse<T> apiResponse = new ApiResponse<>();
        apiResponse.setSuccess(model.getSuccess());
        apiResponse.setError(model.getError());
        return apiResponse;
    }

    /**
     * 构建统一数据返回
     *
     * @param model
     * @param data
     * @param <T>
     * @return
     */
    public static <T> ApiResponse<T> buildApiResponse(ApiResponse<?> model, T data) {
        ApiResponse<T> apiResponse = new ApiResponse<>();
        apiResponse.setSuccess(model.getSuccess());
        apiResponse.setError(model.getError());
        apiResponse.setData(data);
        return apiResponse;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

}
